<?php
namespace App\Services;
use Illuminate\Support\Facades\Redis;
use GuzzleHttp\Client;
use Exception,Log;
use App\Models\Linkslistsminappsapi;

class ThirdapiService
{
    public static function apiGetThirdAccessToken($appid)
    {
        $accessToken = Redis::get("miniapp_api_token_".$appid);
        if (empty($accessToken)) {
            $accessTokenApi = Linkslistsminappsapi::getLinksListsMinappsApiByAppid($appid);
            if (empty($accessTokenApi)) return ["status"=>"error","msg"=>"API接口未配置"];
            $key = time();
            $sign = md5($key.$accessTokenApi->users_code.$key);
            try {
                $client = new Client;
                if(strpos($accessTokenApi->host,'?') !== false){
                    $requestHost = $accessTokenApi->host.'&key='.$key.'&sign='.$sign;
                } else {
                    $requestHost = $accessTokenApi->host.'?key='.$key.'&sign='.$sign;
                }
                $response = $client->request('GET', $requestHost);
                $body = $response->getBody()->getContents();
                $responsebody = json_decode($body);
                if ($responsebody->status == "error") return ["status"=>"error","msg"=>$responsebody->msg];
                Redis::setex("miniapp_api_token_".$appid, 7200, json_encode(["access_token"=>$responsebody->access_token,"expire_time"=>$responsebody->expire_time]));
                return ["status"=>"success","access_token"=>$responsebody->access_token,"expire_time"=>$responsebody->expire_time];
            } catch (Exception $e) {
                return ["status"=>"error","msg"=>"API接口异常"];
            }
        } else {
            $accessTokens = json_decode($accessToken);
            return ["status"=>"success","access_token"=>$accessTokens->access_token,"expire_time"=>$accessTokens->expire_time];
        }
    }
}
